/*************************************************************************
	> File Name: cancel.c
	> Author: 
	> Mail: 
	> Created Time: 2015年01月14日 星期三 16时34分17秒
 ************************************************************************/

#include <pthread.h>
#include "errors.h"

static int counter;

void * thread_routine(void * arg){
    printf("thread_routine starting \n");

    for(counter = 0;;counter++){
        if(counter % 1000 == 0){
            printf("calling tescancel :%d \n" ,counter);
            pthread_testcancel();
        }
    }
}

int main(int argc , char *argv[]){
    pthread_t thread_id;
    void *result;
    int status;


    status = pthread_create(&thread_id,NULL,thread_routine,NULL);
    if(status)  err_abort(status,"Created thread ");

    sleep(2);

    printf("calling cancel \n");

    status = pthread_cancel(thread_id);
    if(status)  err_abort(status,"Cancel thread ");

    printf("calling join\n");

    status = pthread_join(thread_id,&result);
    if(status) err_abort(status, "Join thread");

    if(result == PTHREAD_CANCELED)
        printf("Thread canceled at iteration %d\n",counter);
    else
        printf("Thread is not canceled\n");

    return 0;
}

